package downloadImages;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URL;
import java.util.Scanner;

public class DemoMain{

    public static void main(String[] args) {
        // 提示信息
        System.out.println("1.请确保要保存的盘符没有wchatDownloadImages文件夹，否则会覆盖原文件夹！");
        System.out.println("2.目标网址只能为微信文章的网址，其他网址无法获取(微信打开文章后使用浏览器打开，然后复制导航栏中的网址)");
        System.out.println("3.图片会下载在指定盘符下的wchatDownloadImages文件夹中");
        System.out.println("此程序仅供学习交流使用，出现如何问题概不负责");
        System.out.println("按回车键继续...");
        Enter();

        // 获得要保存的位置和目标网址
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入目标网址：");
        String url = sc.next();

        System.out.println("请输入要存储在什么盘符(如：D / C / E 等)：");
        String pathName = sc.next().toUpperCase();

        // 记录程序运行时间
        long s = System.currentTimeMillis();

        // 开始下载
        jsoupUtils(url, pathName);

        // 输出程序共用时多长时间
        long e = System.currentTimeMillis();
        System.out.println("下载图片用时：" + (e-s) + "毫秒");
        System.out.println("按回车键退出");
        Enter();
    }

    public static void Enter(){
        try {
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void jsoupUtils(String url, String pathName){
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            Document document = Jsoup.parse(new URL(url), 10000);
            Element content = document.getElementById("js_content");
            Elements imgs = content.getElementsByTag("img");

            int id = 1;

            for (Element img : imgs) {
                String imgUrl = img.attr("data-src");
                // 获取输入流
                inputStream = new URL(imgUrl).openConnection().getInputStream();
                // 获取输出流
                File file = new File(pathName + ":\\wchatDownloadImages");
                file.mkdirs();
                File newFile = new File(file,id + ".jpg");
                newFile.createNewFile();
                outputStream = new FileOutputStream(newFile);

                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1){
                    outputStream.write(bytes, 0 ,len);
                }
                System.out.println(id + ".jpg下载完毕");
                id++;

            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally{

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

    }

}
